package com.zhida.jiyangcenter.setting

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.startActivity
import chooongg.base.utils.tipFail
import chooongg.base.utils.tipSuccess
import chooongg.http.APIException
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIAccount
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.PersonalInfoEntity
import com.zhida.jiyangcenter.dialog.AssessmentDialog
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.utils.GlideEngine
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.actiivty_user_info.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.File

@TitleBar(false)
@ContentLayout(R.layout.actiivty_user_info)
class UserInfoActivity : BaseActivity() {
    companion object {
        const val REQUEST_PORTRAIT = 0x001
    }

    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.title("个人信息")
        btn_portrait.setOnClickListener {
            PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .previewImage(false)
                .isCamera(true)
                .isZoomAnim(true)
                .enableCrop(true)
                .withAspectRatio(1, 1)
                .circleDimmedLayer(true)
                .showCropFrame(false)
                .showCropGrid(false)
                .isDragFrame(true)
                .rotateEnabled(true)
                .scaleEnabled(true)
                .forResult(REQUEST_PORTRAIT)
        }
        btn_nick_name.setOnClickListener {
            startActivity<EditNikeNameActivity> {
                putExtra("type", "nickname")
                putExtra("context", tv_nick_name.text.toString())
                putExtra("title", "修改昵称")
            }
        }
        btn_member_id.setOnClickListener {
            val dialog = AssessmentDialog()
            dialog.setListener {
                lifecycleScope.request({ APIAccount.service().sexAdd(if (it == 0) "1" else "2") },
                    object : BaseAPI<Any>() {
                        override fun onSuccess(t: Any?, state: Int, msg: String) {
                            tipSuccess(msg)
                            getData()
                        }

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }

                    })
                dialog.dismiss()
            }
            dialog.show(supportFragmentManager, "userInfo")
        }
    }

    override fun onResume() {
        super.onResume()
        getData()
    }

    private fun getData() {
        lifecycleScope.request({ APIAccount.service().personalInfo() },
            object : BaseAPI<PersonalInfoEntity>() {
                override fun onSuccess(t: PersonalInfoEntity?, state: Int, msg: String) {
                    glideImage(iv_portrait, t?.avatar_path ?: "")
                    tv_nick_name.text = t?.nickname ?: ""
                    tv_member_id.text = t?.gender ?: ""
                    tv_member_city.text = t?.area ?: ""
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_PORTRAIT) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                val selectList = PictureSelector.obtainMultipleResult(data)
                uploadPortrait(
                    selectList[0].mimeType, File(
                        when {
                            !selectList[0].compressPath.isNullOrEmpty() -> selectList[0].compressPath
                            !selectList[0].cutPath.isNullOrEmpty() -> selectList[0].cutPath
                            !selectList[0].androidQToPath.isNullOrEmpty() -> selectList[0].androidQToPath
                            else -> selectList[0].path
                        }
                    )
                )
            }
        }
    }

    private fun uploadPortrait(mimeType: String, image: File) {
        showTipLoading("提交中")
        val datas = HashMap<String, RequestBody>()
        val requestPaymentCodeBody = RequestBody.create(MediaType.parse(mimeType), image)
        datas["pic\"; filename=\"" + image.name] = requestPaymentCodeBody
        lifecycleScope.request({ APIAccount.service().picture(datas) }, object : BaseAPI<Any>() {
            override fun onSuccess(t: Any?, state: Int, msg: String) {
                tipSuccess(msg)
                hideTipLoading()
                getData()
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
                hideTipLoading()
            }

        })

    }
}